<?php
/*
Module Group: verifyCode
Module Group Name: 验证码
Description: 验证码插件用于生成并发放验证码
Version: 1.0
Iconurl: http://www.happyidea.com.cn/resource/wx_icon/verifycode.png
Author: lr
Modules: verifyCode,verifyCodeClaim
Display: 1
*/
class verifyCodeModule extends Module {
	/*
	 * 在构造函数中装载所依赖的类或其他文件
	*/
	function __construct() {
		$this->includePhp('verifyCode', 'verifyCode');
	}
	
	/*
	 * 激活创建数据库
	*/
	public function activate() {
		Module::importSQL(module_sql_path('verifyCode'));
	}
	
	
	public function run($message, $material, $status) {
		$VerifyCode = M("module_verify_code");
		$User = M('user');
		$mid =$material->id;
// 		Log::write('material id is:'.$mid);
		switch ($message->msgType) {
			case 'text':
			case 'event':
				{
					$materialObj = simplexml_load_string($material->xml,
							'SimpleXMLElement', LIBXML_NOCDATA);
					$reward = (String)$materialObj->reward;
					$isCreate = $materialObj->iscreate;
					$fromUserName = $message->fromUserName;
					$isLucky = $materialObj->islucky;
					
					$rm = $message->reply(message_type_text);
					
					$rewardTotalCount = verifyCode::getRewardTotalNum($mid);
// 					$rewardArr = verifyCode::getRewardTotalNum($mid);
// 					
					// 先分割reward
					//$rewardArr = explode(',', $reward);
					// 多个reward时则认为是分配已有验证码
					if ($rewardTotalCount[0]['totalNum'] > 1) {
// 					if (count($rewardArr) > 1) {
// 						$mapArr = array();
// 						foreach ($rewardArr as $tempReward) {
// 							array_push($mapArr, array('eq', $tempReward['reward']));
// 						}
// 						array_push($mapArr, 'or');
// 						$map['reward'] = $mapArr;
						
						$map['fromUserName'] = $fromUserName;
						$map['materialId'] = $mid;
// 						$map['_logic'] = 'and';
						$result = $VerifyCode->where($map)->find();
						
						if (!$result) {
							$map['isClaim'] = 0;
							$map['fromUserName'] = array('eq', '');
							$codeArr = $VerifyCode->where($map)->select();
							if ($codeArr) {
								$arrIndex = array_rand($codeArr, 1);
								$code = $codeArr[$arrIndex]['code'];
								$reward = $codeArr[$arrIndex]['reward'];
// 								$VerifyCode->where("code='$code'")->setField('fromUserName',$fromUserName);
// 								Log::write('save claim code sql is:'.$VerifyCode->getLastSql());
// 								$VerifyCode->where("code='$code'")->setField('createTime',date('Y-m-d H:i:s'));
// 								Log::write('save claim code sql is:'.$VerifyCode->getLastSql());
								$vdata['fromUserName'] = $fromUserName;
								$vdata['createTime'] = date('Y-m-d H:i:s');
								$vresult = $VerifyCode->where("code=$code")->save($vdata);
							}
							else{
								// 读取素材中的活动已结束错误
								$materialErrorDone = $materialObj->errordone;
								$rm->content = $materialErrorDone;
								return $rm;
							}
						} else {
							$result = (object)$result;
							$code = $result->code;
							$reward = $result->reward;
							$isClaim = $result->isClaim;
							if ($isClaim) {
								$materialErrorClaimed = $materialObj->errorclaimed;
								$rm->content = $materialErrorClaimed;
								return $rm;
							}
						}
					} else if ($isCreate == 1) {
						// 判断验证码个数是否超出总量
						$total = (int)$materialObj->total;
						$condition['reward'] = array("eq",$reward);
						$condition['materialId'] = array("eq",$mid);
						$count = (int)$VerifyCode->where($condition)->count();
						Log::write('verifyCode sql is:'.$VerifyCode->getLastSql());
						Log::write($count);
						Log::write($total);
						if ($count >= $total) {
							// 读取素材中的活动已结束错误
							$materialErrorDone = $materialObj->errordone;
							$rm->content = $materialErrorDone;
							return $rm;
						}
						
						
						// 如果验证码已经存在，重新生成
						if (!$VerifyCode->where("fromUserName='$fromUserName' AND  reward='$reward' AND materialId = '$mid'")->find()) {
							$result = $this->createCode($fromUserName, (String)$materialObj->reward,1,$mid);
							if (!$result) {
								// 读取素材中的插入数据错误
								$materialErrorAdd = $materialObj->erroradd;
								$rm->content = $materialErrorAdd;
								return $rm;
							}
							$code = $VerifyCode->where("fromUserName='$fromUserName' AND reward='$reward' AND materialId = '$mid'")->getField('code');
						} else {
							$isClaim = $VerifyCode->where("fromUserName='$fromUserName' AND  reward='$reward' AND materialId = '$mid'")->getField('isClaim');
							if ($isClaim) {
								$materialErrorClaimed = $materialObj->errorclaimed;
								$rm->content = $materialErrorClaimed;
								return $rm;
							}
							$code = $VerifyCode->where("fromUserName='$fromUserName' AND  reward='$reward' AND materialId = '$mid'")->getField('code');
						}
					} else {
						$code = $VerifyCode->where("fromUserName='$fromUserName' AND  reward='$reward' AND materialId = '$mid'")->getField('code');
					}

					
					if (!isset($code)) {
						$materialErrorNotFound = $materialObj->errornotfound;
						$rm->content = $materialErrorNotFound;
						return $rm;
					}
					
					// 替换素材欢迎语中的活动名称和验证码
					$materialWelcome = $materialObj->welcome;
					$isShowUserID = $materialObj->isshowuserid;	
					
					$userID = $User->where("userName='$fromUserName'")->getField('id');
					$codeCreateTime = $VerifyCode->where("fromUserName='$fromUserName' AND  reward='$reward' AND materialId = '$mid'")->getField('createTime');
					
					if($isLucky == 1){
						$materialLucky = $materialObj->lucky;
						$materialCommon = $materialObj->common;
						$materialLuckNum = $materialObj->luckynum;
						
						//判断userId尾数是77的用户
						if(!isset($userID)) {
							$User->create();
							$User->userName = $fromUserName;
							$userID = $User->add();
						}
						$userIDStr = $userID."";
						
						$luckNumLength = strlen((string)$materialLuckNum);
						Log::write('luckNumLength is :'.$luckNumLength);
						$userIDLen = strlen($userIDStr);
						if($userIDLen >= $luckNumLength){
							$mantissa = substr($userIDStr, strlen($userIDStr)-$luckNumLength);
							if($mantissa == $materialLuckNum){
								$xml = str_replace(
										array('{reward}','{code}','{lucky}'),
										array($reward,$code,
												str_replace(array('UserId','codeCreateTime'), array($userIDStr,$codeCreateTime), $materialLucky)),
										$materialWelcome
								);
							}else{
								if($isShowUserID == 1){
									$xml = str_replace(
											array('{reward}','{code}','{lucky}'),
											array($reward,$code,str_replace('UserId', $userIDStr, $materialCommon)),
											$materialWelcome
											);
								}else{
									$xml = str_replace(
											array('{reward}','{code}','{lucky}'),
											array($reward,$code,''),
											$materialWelcome
											);
								}
						}
							
						}else{
							if($isShowUserID == 1){
								$xml = str_replace(
										array('{reward}','{code}','{lucky}'),
										array($reward,$code,str_replace('UserId', $userIDStr, $materialCommon)),
										$materialWelcome
								);
							}else{
								$xml = str_replace(
										array('{reward}','{code}','{lucky}'),
										array($reward,$code,''),
										$materialWelcome
								);
							}
						}
						
					}else{
// 						$xml = str_replace('{reward}', $reward, $materialWelcome);
// 						$xml = str_replace('{code}', $code, $xml);
						
// 						Log::write('reward is :'.$reward);
// 						Log::write('code is :'.$code);
						$xml = str_replace(
								array('{reward}','{code}','{lucky}'),
								array($reward,$code,''),
								$materialWelcome
						);
						
					}
					
					if ($materialObj->isprintcode == 1){
						$feyinDeviceNo = $materialObj->feyindn;
						$printFormat =  $materialObj->printformat;
						if ($feyinDeviceNo != '' && $printFormat != '') {
							$this->printCode($feyinDeviceNo, $printFormat, $reward, $code);
						} else {
							Log::write("VerifyCode Print material set error");
						}
					}
					
					// 读取素材
					$rm->content = $xml;
					return $rm;
				}
				break;
		}
	}
	
	/*
	 * 创建验证码
	 */
	private function createCode($fromUserName, $reward, $count = 1,$mid=null) {
		$VerifyCode = M("module_verify_code");
		$data = array();
		for ($i = 0; $i < $count; $i++) {
			$condition['fromUserName'] = array('eq',$fromUserName);
			$condition['reward'] = array('eq',$reward);
			//$condition['materialIid'] = array('eq',$mid);
			if ($fromUserName != "" && $VerifyCode->where($condition)->find()) {
				continue;
			}
// 			if ($VerifyCode->where("fromUserName='$fromUserName' AND reward='$reward'")->find()) {
// 				continue;
// 			}
			// 生成验证码如果数据库中已经存在则重新生成
			do {
				// 生成6位随机验证码
				$code = rand(100000, 999999);
			} while ($VerifyCode->where("code='$code'")->find());
			
			// 将验证码存储到数据库
			$data[$i]['fromUserName'] = $fromUserName;
			$data[$i]['reward'] = $reward;
			$data[$i]['code'] = (String)$code;
			$data[$i]['materialId'] = $mid;
			$data[$i]['createTime'] = date('Y-m-d H:i:s');
		}
		$result = $VerifyCode->addAll($data);
		return $result;
	}
	
	private function printCode($feyinDeviceNo, $printFormat, $reward, $code) {
		$msg = str_replace("{reward}", $reward, $printFormat);
		$msg = str_replace("{code}", $code, $msg);
		$freeMessage = array(
				'msgDetail' => $msg,
				'deviceNo' => $feyinDeviceNo,
		);
		echo Feyin::sendFreeMessage($freeMessage);
	}
	
	/*
	 * 调用插件资源
	*/
	public function call($user, $method, $param) {
		switch ($method) {
// 			case 'verify':
// 				verifyCode::verify($param->code);
// 				break;
// 			case 'claim':
// 				verifyCode::claim($param->code, $param->branch);
// 				break;
			case 'create':
				$fromUserName = $param->fromUserName;
				if (!isset($fromUserName)) {
					$fromUserName = '';
				}
				$reward = $param->reward;
				$count = $param->count;
				$mid = $param->mid;
				$result = $this->createCode($fromUserName, $reward, $count,$mid);
				if (!$result) {
					Output::instance()->resultCode(code_custom_error, "添加失败");
				} else {
					Output::instance()->resultCode(code_success, "添加成功");
				}
				break;
			case 'verifycode_create':
				Output::instance()->module('verifyCode', 'verifycode_create')->object();
				break;
			case 'verifycode_list':
				verifyCode::getList(false);
				break;
			case 'rewardStatistics':
				verifyCode::rewardStatistics($param->mid);
				break;
				
			case 'getCreateAndClaimStatistics':
				//$mid,$reward,$startDate='',$endDate=''
				verifyCode::getCreateAndClaimStatistics($param->mid,$param->reward,$param->startDate,$param->endDate);
				break;
			case 'getQuerySystemStatistics':

				Log::write('startDate is:'.$param->startDate);
				Log::write('endDate is:'.$param->endDate);
				if(isset($param->branch)){
					verifyCode::getQuerySystemStatistics($param->mid,$param->startDate,$param->endDate,$param->branch);
				}else{
					verifyCode::getQuerySystemStatistics($param->mid,$param->startDate,$param->endDate);
				}
				break;
				
			case 'getQuerySystemByReward':
					verifyCode::getQuerySystemByReward($param->mid,$param->reward,$param->startDate,$param->endDate);
					break;
		}
	}
	
}

$module = new verifyCodeModule();
Module::addModule($module);
?>